<template>
    <view class="container">
      <view class="title">考试安排</view>
      
      <view v-if="!currentExam" class="loading-container">
        <text v-if="loading">加载中...</text>
        <text v-else>暂无考试信息</text>
      </view>
      
      <block v-else>
        <view class="exam-info card">
          <view class="exam-header">
            <view class="exam-name">{{ currentExam.name }}</view>
            <view class="exam-status" :class="getStatusClass(currentExam.status)">
              {{ getStatusText(currentExam.status) }}
            </view>
          </view>
          
          <view class="exam-detail">
            <view class="detail-item">
              <text class="detail-label">考试科目：</text>
              <text class="detail-value">{{ getExamTypeText(currentExam.exam_type) }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">考试地点：</text>
              <text class="detail-value">{{ currentExam.location || '待定' }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">考试时间：</text>
              <text class="detail-value">{{ formatDate(currentExam.exam_date, 'YYYY-MM-DD HH:mm') }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">报名截止：</text>
              <text class="detail-value">{{ formatDate(currentExam.registration_deadline, 'YYYY-MM-DD HH:mm') }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">报名人数：</text>
              <text class="detail-value">{{ currentExam.current_applicants }}/{{ currentExam.max_applicants }}</text>
            </view>
          </view>
          
          <view class="exam-description" v-if="currentExam.description">
            <view class="description-title">考试说明</view>
            <view class="description-content">{{ currentExam.description }}</view>
          </view>
        </view>
        
        <view class="registration-card card" v-if="registrationInfo">
          <view class="registration-title">我的报名状态</view>
          <view class="registration-status">
            <text class="status-label">状态：</text>
            <text class="status-value" :class="getRegistrationStatusClass(registrationInfo.status)">
              {{ getRegistrationStatusText(registrationInfo.status) }}
            </text>
          </view>
          <view class="registration-detail" v-if="registrationInfo.status === 'completed'">
            <view class="registration-score">
              <text class="score-label">得分：</text>
              <text class="score-value" :class="{ 'score-pass': registrationInfo.is_passed, 'score-fail': !registrationInfo.is_passed }">
                {{ registrationInfo.score }}
              </text>
            </view>
            <view class="registration-result">
              <text class="result-label">结果：</text>
              <text class="result-value" :class="{ 'result-pass': registrationInfo.is_passed, 'result-fail': !registrationInfo.is_passed }">
                {{ registrationInfo.is_passed ? '通过' : '未通过' }}
              </text>
            </view>
          </view>
        </view>
        
        <view class="action-container">
          <button 
            class="btn-primary" 
            v-if="!registrationInfo && canRegister()" 
            @click="registerExam"
          >
            立即报名
          </button>
          
          <button 
            class="btn-danger" 
            v-if="registrationInfo && ['pending', 'approved'].includes(registrationInfo.status)" 
            @click="cancelRegistration"
          >
            取消报名
          </button>
          
          <button 
            class="btn-default" 
            style="margin-top: 20rpx;" 
            @click="navigateBack"
          >
            返回
          </button>
        </view>
      </block>
    </view>
  </template>
  
  <script>
  import { mapActions, mapGetters } from 'vuex';
  import { formatDate } from '@/utils/date';
  import config from '@/config/index';
  
  export default {
    data() {
      return {
        examId: '',
        loading: true,
        registrationInfo: null
      };
    },
    computed: {
      ...mapGetters('exam', [
        'currentExam',
        'myExams'
      ])
    },
    onLoad(options) {
      if (options.id) {
        this.examId = options.id;
        this.loadExamData();
      } else {
        this.loading = false;
      }
    },
    methods: {
      ...mapActions('exam', [
        'getExam',
        'getMyExams',
        'registerExam',
        'cancelExamRegistration'
      ]),
      navigateBack() {
        uni.navigateBack();
      },
      formatDate,
      loadExamData() {
        this.loading = true;
        
        // 获取考试详情
        this.getExam(this.examId).then(() => {
          // 获取我的考试报名信息
          return this.getMyExams();
        }).then(() => {
          // 查找当前考试的报名信息
          this.registrationInfo = this.myExams.find(item => item.exam_id === this.examId);
          this.loading = false;
        }).catch(err => {
          this.loading = false;
          this.showToast(err.message || '获取考试信息失败');
        });
      },
      getStatusText(status) {
        const statusMap = {
          'upcoming': '即将开始',
          'ongoing': '进行中',
          'completed': '已结束',
          'cancelled': '已取消'
        };
        return statusMap[status] || status;
      },
      getStatusClass(status) {
        const classMap = {
          'upcoming': 'status-upcoming',
          'ongoing': 'status-ongoing',
          'completed': 'status-completed',
          'cancelled': 'status-cancelled'
        };
        return classMap[status] || '';
      },
      getExamTypeText(type) {
        const examType = config.examSubjects.find(item => item.value === type);
        return examType ? examType.label : type;
      },
      getRegistrationStatusText(status) {
        const statusMap = {
          'pending': '待审核',
          'approved': '已通过',
          'rejected': '已拒绝',
          'completed': '已完成'
        };
        return statusMap[status] || status;
      },
      getRegistrationStatusClass(status) {
        const classMap = {
          'pending': 'status-pending',
          'approved': 'status-approved',
          'rejected': 'status-rejected',
          'completed': 'status-completed'
        };
        return classMap[status] || '';
      },
      canRegister() {
        if (!this.currentExam) return false;
        
        // 判断是否可以报名考试
        if (this.currentExam.status !== 'upcoming') {
          return false;
        }
        
        if (this.currentExam.current_applicants >= this.currentExam.max_applicants) {
          return false;
        }
        
        // 判断是否超过报名截止日期
        const now = new Date();
        const deadline = new Date(this.currentExam.registration_deadline);
        if (now > deadline) {
          return false;
        }
        
        return true;
      },
      registerExam() {
        if (!this.canRegister()) return;
        
        this.showModal(`确认报名参加 ${this.currentExam.name} 吗？`)
          .then(confirm => {
            if (confirm) {
              uni.showLoading({
                title: '报名中...'
              });
              
              this.registerExam(this.examId)
                .then(() => {
                  this.showToast('报名成功', 'success');
                  // 重新加载数据
                  this.loadExamData();
                })
                .catch(err => {
                  this.showToast(err.message || '报名失败');
                })
                .finally(() => {
                  uni.hideLoading();
                });
            }
          });
      },
      cancelRegistration() {
        this.showModal('确认取消报名吗？')
          .then(confirm => {
            if (confirm) {
              uni.showLoading({
                title: '取消中...'
              });
              
              this.cancelExamRegistration(this.examId)
                .then(() => {
                  this.showToast('取消报名成功', 'success');
                  // 重新加载数据
                  this.loadExamData();
                })
                .catch(err => {
                  this.showToast(err.message || '取消报名失败');
                })
                .finally(() => {
                  uni.hideLoading();
                });
            }
          });
      }
    }
  };
  </script>
  
  <style lang="scss">
  .container {
    padding: 30rpx;
  }
  
  .title {
    font-size: 36rpx;
    font-weight: bold;
    text-align: center;
    margin-bottom: 40rpx;
  }
  
  .loading-container {
    text-align: center;
    padding: 60rpx 0;
    color: #999;
  }
  
  .exam-info, .registration-card {
    padding: 30rpx;
    margin-bottom: 30rpx;
  }
  
  .exam-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 30rpx;
  }
  
  .exam-name {
    font-size: 32rpx;
    font-weight: bold;
  }
  
  .exam-status {
    font-size: 24rpx;
    padding: 4rpx 16rpx;
    border-radius: 20rpx;
  }
  
  .status-upcoming {
    background-color: #e6f7ff;
    color: #1890ff;
  }
  
  .status-ongoing {
    background-color: #fff7e6;
    color: #e6a23c;
  }
  
  .status-completed {
    background-color: #e6f7f0;
    color: #52c41a;
  }
  
  .status-cancelled {
    background-color: #fff3f3;
    color: #f56c6c;
  }
  
  .status-pending {
    background-color: #fff7e6;
    color: #e6a23c;
  }
  
  .status-approved {
    background-color: #e6f7f0;
    color: #52c41a;
  }
  
  .status-rejected {
    background-color: #fff3f3;
    color: #f56c6c;
  }
  
  .status-completed {
    background-color: #e6f7ff;
    color: #1890ff;
  }
  
  .exam-detail {
    margin-bottom: 30rpx;
  }
  
  .detail-item {
    display: flex;
    margin-bottom: 16rpx;
  }
  
  .detail-label {
    width: 160rpx;
    font-size: 28rpx;
    color: #666;
  }
  
  .detail-value {
    flex: 1;
    font-size: 28rpx;
    color: #333;
  }
  
  .exam-description {
    padding-top: 20rpx;
    border-top: 1px solid #eee;
  }
  
  .description-title {
    font-size: 30rpx;
    font-weight: bold;
    margin-bottom: 16rpx;
  }
  
  .description-content {
    font-size: 28rpx;
    color: #666;
    line-height: 1.6;
  }
  
  .registration-title {
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 30rpx;
    text-align: center;
  }
  
  .registration-status {
    display: flex;
    justify-content: center;
    margin-bottom: 30rpx;
  }
  
  .status-label {
    font-size: 30rpx;
    color: #666;
  }
  
  .status-value {
    font-size: 30rpx;
    font-weight: bold;
    margin-left: 10rpx;
  }
  
  .registration-detail {
    display: flex;
    justify-content: space-around;
  }
  
  .registration-score, .registration-result {
    display: flex;
    align-items: center;
  }
  
  .score-label, .result-label {
    font-size: 28rpx;
    color: #666;
  }
  
  .score-value, .result-value {
    font-size: 32rpx;
    font-weight: bold;
    margin-left: 10rpx;
  }
  
  .score-pass, .result-pass {
    color: #52c41a;
  }
  
  .score-fail, .result-fail {
    color: #f56c6c;
  }
  
  .action-container {
    margin-top: 60rpx;
  }
  
  .btn-primary, .btn-danger, .btn-default {
    width: 100%;
    height: 90rpx;
    line-height: 90rpx;
    font-size: 32rpx;
    border-radius: 8rpx;
  }
  
  .btn-primary {
    color: #fff;
    background-color: #3c8dbc;
  }
  
  .btn-danger {
    color: #fff;
    background-color: #f56c6c;
  }
  
  .btn-default {
    color: #666;
    background-color: #f8f8f8;
    border: 1px solid #ddd;
  }
  </style>